package com.sslpay.merchant.common.intercept;

import com.sslpay.common.domain.RestResponse;
import com.sslpay.merchant.common.domain.MerchantApplicationErrorCode;
import com.sslpay.merchant.common.domain.MerchantApplicationException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.MissingServletRequestParameterException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.method.annotation.MethodArgumentTypeMismatchException;
import org.springframework.web.servlet.NoHandlerFoundException;

import java.text.MessageFormat;

/**
 * 描述：全局异常处理
 *
 * @author ssl
 * @create 2020/04/30 16:58
 */
@ControllerAdvice
public class GlobalExceptionHandler {
    private static final Logger LOGGER = LoggerFactory.getLogger(GlobalExceptionHandler.class);


    @ExceptionHandler(value = Exception.class)
    @ResponseBody
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    public RestResponse processException(Exception e) {
        // 自定义异常
        MerchantApplicationErrorCode errorCode = MerchantApplicationErrorCode.UNKNOWN;
        if (e instanceof MerchantApplicationException) {
            MerchantApplicationException e1 = (MerchantApplicationException) e;
            errorCode = e1.getErrorCode();
        } else if (e instanceof MissingServletRequestParameterException) {
            //缺少参数异常
            MissingServletRequestParameterException e1 = (MissingServletRequestParameterException) e;
            String msg = MessageFormat.format("参数 [{0}] 不能为空", e1.getParameterName());
            errorCode = MerchantApplicationErrorCode.M_E_100101;
            errorCode.setMsg(msg);
        } else if (e instanceof MethodArgumentTypeMismatchException) {
            //参数类型异常
            MethodArgumentTypeMismatchException e1 = (MethodArgumentTypeMismatchException) e;
            String msg = MessageFormat.format("参数 [{0}] 类型不正确", e1.getName());
            errorCode = MerchantApplicationErrorCode.M_E_100101;
            errorCode.setMsg(msg);
        } else if (e instanceof NoHandlerFoundException) {
            // 请求资源不存在
            errorCode = MerchantApplicationErrorCode.M_E_100102;
        } else if (e instanceof HttpRequestMethodNotSupportedException) {
            // 不支持的请求方式
            errorCode = MerchantApplicationErrorCode.M_E_100103;
        }
        LOGGER.error(errorCode.getMsg(), e);
        return RestResponse.fail(errorCode);
    }
}
